import urllib
import urllib2
import simplejson
import ConfigParser
import os
import codecs
import sys
import getopt

# This Google API URL is called for translating text
GOOGLE_API_URL = 'https://ajax.googleapis.com/ajax/services/language/translate'

# Import the configuration settings from the file config.py
config = __import__('config')
_debug = False

# Referer URL is a mandatory parameter for the API, set it to your website in config.py
refererURLText = "{'Referer': '" + config.REFERER_URL + "'}"

# Return the base (common) URL for translations
# To this, the input/output language and text to translate should be added before invocation
def _get_base_url():
	theURL = GOOGLE_API_URL + "?v=1.0"
	theURL += "&userip=" + config.IP_ADDR
	theURL += "&key=" + config.GOOGLE_API_KEY

	return theURL

# The main function that is responsible for translating an input string from source language to
# target language. It invokes the Google API
def _get_translated_text(inputString, inLangCode, outLangCode):
	# Build the request URL
	languagePair = "&langpair=" + inLangCode + "%7C" + outLangCode
	questionStr  = "&q=" + urllib.quote_plus(inputString)
	translateURL = _get_base_url() + languagePair + questionStr

	if _debug:
		print ("URL: " + translateURL)

	# Create the request and send it to Google
	request = urllib2.Request(translateURL, None, {}, refererURLText)
	response = urllib2.urlopen(request)

	# Parse the JSON response	
	result = simplejson.load(response)

	if result != None and result['responseData'] != None and result['responseData']['translatedText'] != None:
		return result['responseData']['translatedText']
	else:
		return ""
	
# This function parses the input properties file and returns a list of key,value pairs
def _parse_input_file(filename):
	# Before parsing the input file copy its contents into a temporary file
	# The first line of the temporary file should contain a dummy section header
	# This is required because the class ConfigParser requires a section header to be present

	tempfileName = filename + '_tmp'
	tempfile = open(tempfileName, "w")
	sourceFile = open(filename)
	tempfile.write("[DummySectionHeader]");

	for line in sourceFile.readlines():
		tempfile.write(line)

	sourceFile.close()
	tempfile.close()

	# Now parse the properties file
	parser = ConfigParser.ConfigParser()
	parser.read(tempfileName)

	# Remove the temporary file
	os.remove(tempfileName)

	# Return all the entries in the properties file
	return parser.items("DummySectionHeader")

# Returns the input number padded with length - len(num) zeros
def _get_padded_str(num, length):
	numstr = str(num)
	while (len(numstr) < length):
		numstr = "0" + numstr

	return numstr

# This function translates the contents of a file (one line at a time)
# from the input language to the output language
def _translate_file(inFilename, outFilename, inLangCode, outLangCode):
	print "Translating file " + inFilename + " from " + inLangCode + " to " + outLangCode

	# Parse the input file
	textItems = _parse_input_file(inFilename)
	
	# Open the output file and write the header
	i = 0
	print "Total lines to translate: " + _get_padded_str(len(textItems), 4)
	outputFile = codecs.open(outFilename, "w", "utf-8")
	outputFile.write("# " + outFilename + " translated from " + inFilename + " using translate.py" + "\n")
	outputFile.write("# " + "input language: " + inLangCode + ", output language: " + outLangCode + "\n")

	if not _debug:
		print "Lines translated so far : 0000",

	# Translate lines one by one and write to the output file
	for item in textItems:
		translation = ""
		if len(item) > 1 and len(item[1]) > 0 :
			translation = _get_translated_text(item[1], inLangCode, outLangCode)
		outputFile.write(item[0] + " = " + translation + "\n")
		i = i + 1
		if _debug:
			print(item[0] + " = " + translation)
		else:
			# This is for a cool effect of incresing the num lines translated in place
			# For the effect, we remove the already printed number and replace it with the updated one
			print "\b\b\b\b\b\b",
			print _get_padded_str(i, 4),
			sys.stdout.flush()
	print "\nDone." 

# Usage of the program
def _usage():
	print "Usage: python translate.py -d -f INPUT_FILE -o OUTPUT_FILE -s SOURCE_LANGUAGE -t TARGET_LANGUAGE"
	print "\t -d: run in debug mode"
	print "\t -f: the input file name"
	print "\t -o: the output file name"
	print "\t -s: the ISO 639-1 code of source language (en by default)"
	print "\t -t: the ISO 639-1 code of target language"
	print "The ISO 639-1 codes for languages can be found at: http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes\n"

# The main program logic
def _main(argv):
	# Parse the command line parameters
	global _debug
	try:
		opts, args = getopt.getopt(argv, "dhf:o:s:t:")
	except getopt.GetoptError as error: 
		print str(error)
		_usage()
		sys.exit(2)

	# Initialize parameters
	inputFile = ""
	outputFile = ""
	inLangCode = "en"
	outLangCode = ""

	for o, a in opts:
		if o == "-d":
			_debug = True
		elif o == "-h":
			_usage()
			sys.exit()
		elif o == "-f":
			inputFile = a
		elif o == "-o":
			outputFile = a
		elif o == "-s":
			inLangCode = a
		elif o == "-t":
			outLangCode = a
		else:
			assert False, "unhandled option"

	if (inputFile == "" or outputFile == "" or inLangCode == "" or outLangCode == ""):
		_usage()
		sys.exit(2)
	else:
		_translate_file(inputFile, outputFile, inLangCode, outLangCode)

# main function
if __name__ == '__main__':
	 _main(sys.argv[1:])

